import sys
import json
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QWidget, QTextEdit, QPushButton,
    QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QSplitter, QMessageBox
)
from PyQt5.QtCore import Qt, QUrl
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply

class DeepSeekChat(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("DeepSeek Chat v3")
        self.setGeometry(100, 100, 800, 600)
        
        # 初始化网络管理器
        self.network_manager = QNetworkAccessManager()
        self.network_manager.finished.connect(self.handle_response)
        
        self.init_ui()
        
    def init_ui(self):
        # 创建主部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QVBoxLayout(central_widget)
        
        # API密钥输入
        self.api_key_entry = QLineEdit()
        self.api_key_entry.setPlaceholderText("输入您的API密钥")
        self.api_key_entry.setEchoMode(QLineEdit.Password)
        main_layout.addWidget(QLabel("DeepSeek API Key:"))
        main_layout.addWidget(self.api_key_entry)
        
        # 分割视图
        splitter = QSplitter(Qt.Vertical)
        
        # 聊天记录显示
        self.chat_history = QTextEdit()
        self.chat_history.setReadOnly(True)
        self.chat_history.setPlaceholderText("聊天记录...")
        
        # Markdown预览
        self.markdown_preview = QTextEdit()
        self.markdown_preview.setReadOnly(True)
        self.markdown_preview.setPlaceholderText("Markdown预览...")
        
        splitter.addWidget(self.chat_history)
        splitter.addWidget(self.markdown_preview)
        splitter.setSizes([400, 200])
        main_layout.addWidget(splitter)
        
        # 输入区域
        input_layout = QHBoxLayout()
        self.user_input = QTextEdit()
        self.user_input.setPlaceholderText("输入您的问题...")
        self.user_input.setMaximumHeight(100)
        self.send_btn = QPushButton("发送")
        self.send_btn.clicked.connect(self.send_request)
        
        input_layout.addWidget(self.user_input)
        input_layout.addWidget(self.send_btn)
        main_layout.addLayout(input_layout)
        
    def send_request(self):
        api_key = self.api_key_entry.text().strip()
        question = self.user_input.toPlainText().strip()
        
        if not api_key:
            QMessageBox.warning(self, "警告", "请输入API密钥")
            return
        if not question:
            QMessageBox.warning(self, "警告", "请输入问题内容")
            return
        
        # 显示用户消息
        self.chat_history.append(f"**You**:\n{question}\n")
        
        # 创建API请求
        url = QUrl("https://api.deepseek.com/v1")
        request = QNetworkRequest(url)
        request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json")
        request.setRawHeader(b"Authorization", f"Bearer {api_key}".encode())
        
        payload = {
            "model": "deepseek-chat",
            "messages": [{"role": "user", "content": question}],
            "temperature": 0.7
        }
        
        # 发送请求
        self.network_manager.post(
            request, 
            json.dumps(payload).encode("utf-8")
        )
        
        # 清空输入框
        self.user_input.clear()
        
    def handle_response(self, reply):
        if reply.error() == QNetworkReply.NoError:
            data = reply.readAll().data()
            try:
                response = json.loads(data)
                content = response["choices"][0]["message"]["content"]
                
                # 更新聊天记录
                self.chat_history.append(f"**AI**:\n{content}\n")
                
                # 显示Markdown预览
                self.markdown_preview.setMarkdown(content)
            except Exception as e:
                QMessageBox.critical(self, "错误", f"解析响应失败: {str(e)}")
        else:
            QMessageBox.critical(
                self, 
                "请求失败", 
                f"错误代码: {reply.error()}\n错误信息: {reply.errorString()}"
            )
        
        reply.deleteLater()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = DeepSeekChat()
    window.show()
    sys.exit(app.exec_())